import router from "../router/index";

import axios from 'axios'

import {Loading} from 'element-ui'

let loading;
function startLoading() {
  loading = Loading.service({
    lock: true,
    text: '拼命加载中....',
    background: 'rgba(0,0,0,0,7)'
  })
}

function endLoading() {
  loading.close();
}

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
//超终极解决方案
export function request(config) {  //外面传函数
  // 1.创建axios实例
  const instance = axios.create({
    baseURL: 'https://classroom.light-year-tech.com:3003',
    // baseURL: 'https://127.0.0.1:3003',
    timeout: 5000,

  })
  // 2.axios的拦截器
  instance.interceptors.request.use(config => {
    // 加载动画
    startLoading();
    if (localStorage.eleToken) {
      // 设置统一的请求header
      config.headers.Authorization = localStorage.eleToken
    }

    return config
  }, err => {
    // console.log(err);
  })
  //响应拦截
  instance.interceptors.response.use(res => {
    // 结束加载
    endLoading();
    return res.data  //记得返回
  }, err => {
    //获取状态码

    const {status} = err.response;
    if (status === 401) {
      // 清除token
      localStorage.removeItem('eleToken')
      // 跳转到登录
      router.push('/login')
      endLoading();
    }

    console.log(err);
  })

  // 3.发送真正的网络请求
  return instance(config)  //返回Promise
}

/**
 * 小程序接口
 */

export function sendSubscriptionMessage(config) {  //外面传函数
  // 1.创建axios实例
  const instance = axios.create({
    baseURL: 'https://classroom.light-year-tech.com:3001',
    // baseURL: 'https://127.0.0.1:3001',
    timeout: 5000,

  })
  // 2.axios的拦截器
  instance.interceptors.request.use(config => {
    if (localStorage.eleToken) {
      // 设置统一的请求header
      config.headers.Authorization = localStorage.eleToken
    }

    return config
  }, err => {
    // console.log(err);
  })
  //响应拦截
  instance.interceptors.response.use(res => {
    // console.log(res);
    return res.data  //记得返回
  }, err => {
    //获取状态码

    const {status} = err.response;
    if (status === 401) {
      // 清除token
      localStorage.removeItem('eleToken')
      // 跳转到登录
      router.push('/login')
    }

    console.log(err);
  })

  // 3.发送真正的网络请求
  return instance(config)  //返回Promise
}